package org.xxpay.task.attachment;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/attachments")
public class AttachmentController {


    @Value("${config.attachmentRootPath}")
    private String attachmentRootPath;

    /**
     * 下载文件
     * @return
     */
    @RequestMapping("**")
    public ResponseEntity<byte[]> get(HttpServletRequest request) {

        try {
            String uri = request.getRequestURI();
            String filePath = uri.substring(uri.indexOf("attachments") + 12, uri.length());
            File file = new File(attachmentRootPath + File.separator + filePath);
            if(!file.exists()) return null;
            byte[] body = null;
            InputStream is = new FileInputStream(file);
            body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            //headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  //下载形式
            HttpStatus statusCode = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            is.close();
            return entity;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}